package com.clw.controller;

import com.clw.converter.PurchaseOrderForm2PurchaseOrderDTOConverter;
import com.clw.converter.ReturnForm2ReturnDTOConverter;
import com.clw.dataobject.*;
import com.clw.dto.PurchaseOrderDTO;
import com.clw.dto.ReturnDTO;
import com.clw.enums.ResultEnum;
import com.clw.form.PurchaseOrderForm;
import com.clw.form.ReturnForm;
import com.clw.service.PurchaseOrderService;
import com.clw.service.ReturnService;
import com.clw.service.SaleService;
import com.clw.utils.NumberUtils;
import com.clw.utils.ResultVOUtils;
import com.clw.utils.StringUtils;
import com.clw.vo.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.*;

/**
 * Created by Administrator on 2018-03-01.
 */
@Controller
@RequestMapping("return_product")
public class ReturnController {
    @Autowired
    private ReturnService service;

    @Autowired
    private PurchaseOrderService purchaseOrderService;

    @Autowired
    private SaleService saleService;

    @RequestMapping("/list")
    public ModelAndView list(){
        return new ModelAndView("return_product/index");
    }

    @ResponseBody
    @RequestMapping("getData")
    public Map<String,Object> getData(@RequestParam(value = "page", defaultValue = "1") Integer page,
                                      @RequestParam(value = "rows", defaultValue = "10") Integer rows,
                                      HttpServletRequest request) {
        PageRequest pageRequest=new PageRequest(page-1,rows);
        String returnNo=request.getParameter("returnNo");
        String startTime=request.getParameter("startTime");
        String endTime=request.getParameter("endTime");
        Map<String,Object> map=new HashMap<>();
        Page<Return> purchaseOrderPage=service.findPage(returnNo,startTime,endTime,pageRequest);
        map.put("rows",purchaseOrderPage.getContent());
        map.put("total",service.getSize(returnNo,startTime,endTime));
        return map;
    }

    @RequestMapping("/view")
    public ModelAndView addView(@RequestParam(value = "id",required = false) Integer id,
                                Map<String,Object> map,HttpSession session){
        Return returnProduct;
        if (StringUtils.isNotEmpty(id)){
            returnProduct=service.findOne(id);
        }
        else{
            returnProduct=new Return();
            returnProduct.setReturnNo(NumberUtils.getMiRandom("return"));
            Integer userId=(Integer) session.getAttribute("user_id");
            returnProduct.setCreateUserId(userId);
        }
        map.put("returnProduct",returnProduct);
        return new ModelAndView("return_product/add_view");
    }

    @RequestMapping("/getDetail")
    @ResponseBody
    public List<ReturnDetail> getDetail(String returnNo){
        return service.getDetail(returnNo);
    }

    @ResponseBody
    @RequestMapping("save")
    public ResultVO save(@Valid ReturnForm form, BindingResult bindingResult){
        if (bindingResult.hasErrors()){
            return ResultVOUtils.error(ResultEnum.PARAM_ERROR.getCode(),bindingResult.getFieldError().getDefaultMessage());
        }
        ReturnDTO returnDTO= ReturnForm2ReturnDTOConverter.convert(form);
        if (!StringUtils.isNotEmpty(form.getId())){
            service.add(returnDTO);
        }
        else {
            Return aReturn=service.findOne(returnDTO.getId());
            if (aReturn.getStatus()!=0){
                return ResultVOUtils.error(ResultEnum.ORDER_STATUS_NOT_ALLOW.getCode(),
                        ResultEnum.ORDER_STATUS_NOT_ALLOW.getMessage());
            }
            service.update(returnDTO);
        }
        return ResultVOUtils.success("保存成功");
    }


    @RequestMapping("del")
    @ResponseBody
    public ResultVO del(@RequestParam(value = "id",required = true) Integer id){
        Return aReturn=service.findOne(id);
        if (aReturn==null){
            return ResultVOUtils.error(ResultEnum.NO_FOUND.getCode(),
                    ResultEnum.NO_FOUND.getMessage());
        }
        if (aReturn.getStatus()!=0){
            return ResultVOUtils.error(ResultEnum.ORDER_STATUS_NOT_ALLOW.getCode(),
                    ResultEnum.ORDER_STATUS_NOT_ALLOW.getMessage());
        }
        service.del(aReturn);
        return ResultVOUtils.success("删除成功");
    }

    @ResponseBody
    @PostMapping("review")
    public ResultVO review(@RequestParam(value = "id",required = false) Integer id,
                           @RequestParam(value = "review",required = false) Integer review,
                           HttpSession session){
        Return aReturn=service.findOne(id);
        if (aReturn==null){
            return ResultVOUtils.error(ResultEnum.NO_FOUND.getCode(),
                    ResultEnum.NO_FOUND.getMessage());
        }
        if (aReturn.getStatus()!=0){
            return ResultVOUtils.error(ResultEnum.ORDER_STATUS_NOT_ALLOW.getCode(),
                    ResultEnum.ORDER_STATUS_NOT_ALLOW.getMessage());
        }
        Integer userId=(Integer) session.getAttribute("user_id");
        if (review==-1){
            aReturn.setStatus(-1);
            aReturn.setReviewTime(new Date());
            aReturn.setReviewUserId(userId);
            service.save(aReturn);

        }
        else{
            aReturn.setStatus(1);
            aReturn.setReviewTime(new Date());
            aReturn.setReviewUserId(userId);
            service.review(aReturn);
        }
        return ResultVOUtils.success("操作成功");
    }

    @ResponseBody
    @RequestMapping("/getOrder")
    public List<Map<String,Object>> getOrder(@RequestParam("code") String code){
        List<Map<String,Object>> list=new ArrayList<>();
        if ("cgth".equals(code)){
            //获取采购订单
            List<PurchaseOrder> purchaseOrders= purchaseOrderService.getAllFinishOrder();
            for (PurchaseOrder purchaseOrder:purchaseOrders) {
                Map<String,Object> map=new HashMap<>();
                map.put("id",purchaseOrder.getId());
                map.put("no",purchaseOrder.getPurNo());
                list.add(map);
            }
        }
        else if ("xsth".equals(code)){
//            获取销售订单
            List<Sale> sales= saleService.getAllFinishOrder();
            for (Sale sale:sales) {
                Map<String,Object> map=new HashMap<>();
                map.put("id",sale.getId());
                map.put("no",sale.getSaleNo());
                list.add(map);
            }
        }
        else {
            Map<String,Object> map=new HashMap<>();
            map.put("id",-1);
            map.put("no","请先选择退货类型");
            list.add(map);
        }
        return list;
    }
}
